import {
  INIT_BOOK_CASE,
  GET_DEL_ITEM_INDEX,
  ADD_ITEM,
  DEL_ITEM,
  CHANGE_ITEM_INDEX,
  DEL_ACTION_SHEET_SHOW,
  DEL_ACTION_SHEET_HIDE
} from './bookCaseMutations'

const bookCase = {
  namespaced: true,
  state: {
    content: [],
    itemIndex: 0,
    delActionSheetIsShow: false
  },
  mutations: {
    // 初始化书架
    [INIT_BOOK_CASE] (state) {
      !localStorage.getItem('bookCaseContent')
        ? localStorage.setItem('bookCaseContent', '[]')
        : state.content = JSON.parse(localStorage.getItem('bookCaseContent'))
    },
    // additem
    [ADD_ITEM] (state, item) {
      let itemWrapper = {
        id: item.id,
        chapterId: item.firstChapterId,
        cover: item.cover,
        title: item.title,
        author: item.author,
        chapter: item.chapter
      }
      !localStorage.getItem('bookCaseContent')
        ? localStorage.setItem('bookCaseContent', '[]')
        : state.content = JSON.parse(localStorage.getItem('bookCaseContent'))
      state.content.unshift(itemWrapper)
      localStorage.setItem('bookCaseContent', JSON.stringify(state.content))
    },
    // 获取待删除项目索引
    [GET_DEL_ITEM_INDEX] (state, index) {
      state.itemIndex = index
    },
    // 删除项目
    [DEL_ITEM] (state) {
      state.content.splice(state.itemIndex, 1)
      localStorage.setItem('bookCaseContent', JSON.stringify(state.content))
    },
    // 变更项目索引
    [CHANGE_ITEM_INDEX] (state, index) {
      if (index !== 0) {
        let item = state.content[index]
        state.content.splice(index, 1)
        state.content.unshift(item)
        localStorage.setItem('bookCaseContent', JSON.stringify(state.content))
      }
    },
    // delActionSheetShow
    [DEL_ACTION_SHEET_SHOW] (state) {
      state.delActionSheetIsShow = true
    },
    // delActionSheetHide
    [DEL_ACTION_SHEET_HIDE] (state) {
      state.delActionSheetIsShow = false
    }
  },
  actions: {
  },
  getters: {}
}

export default bookCase
